#!/usr/bin/env python
# -*- coding:utf-8 -*-

def normalize(numbers):
    total = sum(numbers)
    result = []
    for value in numbers:
        percent = 100.0 * value / total
        result.append(percent)
    return result

def read_visits(data_path):
    with open(data_path) as f:
        for line in f:
            yield int(line)

def normalize_copy(numbers):
    numbers = list(numbers) # copy the iterator
    return normalize(numbers)

def normalize_func(get_iter):
    total = sum(get_iter()) # New iterator
    result = []
    for value in get_iter():# New iterator
        percent = 100.0 * value / total
        result.append(percent)
    return result
        

class ReadVisits(object):
    """
    可迭代的容器类
    """

    def __init__(self, data_path):
        self.data_path = data_path

    def __iter__(self):
        with open(self.data_path) as f:
            for line in f:
                yield int(line)

def normalize_defensive(numbers):
    if iter(numbers) is iter(numbers):  # An interator -- bad! 相等即为迭代器
        raise TypeError('Must supply a container')
    return normalize(numbers)
        
# 1
print('====1====')
visits = [15, 35, 80]
percentages = normalize(visits)
print(percentages)

path = __file__ + '_my_numbers.txt'

# 2
print('====2====')
it = read_visits(path)
# print(it)
percentages = normalize(it)
print(percentages)

# 3
print('====3====')
percentages = normalize_copy(it)
print(percentages)

# 4
print('====4====')
percentages = normalize_func(lambda: read_visits(path))
print(percentages)

# 5
print('====5====')
visits = ReadVisits(path)
percentages = normalize(visits)
print(percentages)

# 6
print('====6====')
visits = [15, 35, 80]
normalize_defensive(visits) # No error
visits = ReadVisits(path)
percentages = normalize_defensive(visits) # No error
print(percentages)

# it = iter(visits)
# normalize_defensive(it)     # Must supply a container
